package com.LachesismStorm.lachesism.downloader;

import com.LachesismStorm.lachesism.core.util.AsyncUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.LachesismStorm.lachesism.core.util.LachesismTools.interceptString;
import static com.LachesismStorm.lachesism.core.util.LachesismTools.sendGet;

public class hypnotubeImageDownloader {
    private static Map<String, Integer> extImageCountMap = new HashMap<>();

    public static void main(String[] args) throws IOException {

        download();
    }

    public static void download() throws IOException {
        String downloadDirectory = "/Users/yuno/Downloads/image";  // 图片保存路径
        ArrayList<String> urls = new ArrayList<>();
        urls.add("https://hypnotube.com/galleries/asspussy-71253.html");
        urls.add("https://hypnotube.com/galleries/bbc-gif-13991.html");
        urls.add("https://hypnotube.com/galleries/gif-hypno-12503.html");
        urls.add("");
        urls.add("");
        urls.add("");


        for (String url : urls) {
            System.out.println("开始下载：" + url + "");
            downloadImages(url, downloadDirectory);
        }
    }

    public static void downloadImages(String url, String downloadDirectory) throws IOException {
        // 连接到网页并获取HTML内容
        Document doc = Jsoup.connect(url).get();
        String ext = url.substring(url.indexOf("galleries/") + "galleries/".length(), url.lastIndexOf("-"));
        // 查找所有符合选择器的元素，获取图片链接
        Elements galleryItems = doc.select("#galleryImages > div[class^=gallery-item-col] > div > a");
        Element item = galleryItems.get(1);
        // 遍历每个div元素，获取href属性中的链接
        String imagePageUrl = item.attr("href");  // 获取图片页面的链接
        if (imagePageUrl != null && !imagePageUrl.isEmpty()) {
            // 通过图片页面链接下载图片
            String html = sendGet(imagePageUrl);
            String s = interceptString(html, "var images = [];", "$(document).ready(function() {");
            List<String> imageLinks = extractImageUrls(s);
            // 遍历所有图片URL，并下载并保存到本地
            for (String imageUrl : imageLinks) {
                AsyncUtil.executeAsync(() -> {
                    try {
                        downloadImage(imageUrl, downloadDirectory, ext);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });

            }
        }

    }

    // 使用正则表达式提取图片链接
    public static List<String> extractImageUrls(String s) {
        List<String> imageUrls = new ArrayList<>();
        // 匹配以 https://media.hypnotube.com 开头的链接，并以 ' 结束
        Pattern pattern = Pattern.compile("https://media\\.hypnotube\\.com/galleries/[^']+");
        Matcher matcher = pattern.matcher(s);

        while (matcher.find()) {
            imageUrls.add(matcher.group());
        }

        return imageUrls;
    }


    // 下载图片并保存到指定目录
    public static void downloadImage(String imageUrl, String downloadDirectory, String ext) throws IOException {
        // 构造图片的URL对象
        URL url = new URL(imageUrl);
        InputStream inputStream = url.openStream();

        // 获取图片格式（例如.jpg, .gif等）
        String fileNameWithParams = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);  // 获取文件名（包括查询参数）
        int paramIndex = fileNameWithParams.indexOf("?token=");
        if (paramIndex != -1) {
            fileNameWithParams = fileNameWithParams.substring(0, paramIndex);  // 如果有查询参数，去掉查询参数部分
        }

        String fileExtension = fileNameWithParams.substring(fileNameWithParams.lastIndexOf("."));
        // 根据ext获取并更新图片编号
        int count = extImageCountMap.getOrDefault(ext, 0);
        extImageCountMap.put(ext, count + 1);  // 更新计数器

        // 使用ext和计数器来命名图片
        String fileName = ext + count + fileExtension;
        Path targetPath = Paths.get(downloadDirectory, fileName);

        // 创建输出文件流，并保存图片
        try (BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(targetPath))) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            System.out.println("Downloaded: " + fileName);
        } catch (IOException e) {
            System.err.println("Failed to download image: " + imageUrl);
            e.printStackTrace();
        } finally {
            inputStream.close();
        }
    }
}
